package com.jcsz.gulimall.ware.service.impl;


import com.jcsz.common.constant.WareConstant;
import com.jcsz.gulimall.ware.dao.WareSkuDao;
import com.jcsz.gulimall.ware.entity.PurchaseDetailEntity;
import com.jcsz.gulimall.ware.service.PurchaseDetailService;
import com.jcsz.gulimall.ware.service.WareSkuService;
import com.jcsz.gulimall.ware.vo.MergeVo;
import com.jcsz.gulimall.ware.vo.PurchaseDoneVo;
import com.jcsz.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jcsz.common.utils.PageUtils;
import com.jcsz.common.utils.Query;

import com.jcsz.gulimall.ware.dao.PurchaseDao;
import com.jcsz.gulimall.ware.entity.PurchaseEntity;
import com.jcsz.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;


    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");

        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(obj -> {
                obj.eq("assignee_id", key).or().like("assignee_name", key);
            });
        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("status", status);
        }

        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params), queryWrapper

        );

        return new PageUtils(page);
    }

    @Override
    public void savePurchase(PurchaseEntity purchase) {
        purchase.setCreateTime(new Date());
        purchase.setUpdateTime(new Date());
        this.save(purchase);
    }

    @Override
    public void updatePurchaseById(PurchaseEntity purchase) {
        purchase.setUpdateTime(new Date());
        this.updateById(purchase);
    }

    @Override
    public PageUtils queryUnreceive(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 0).or().eq("status", 1);
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params), queryWrapper

        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();

        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.savePurchase(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntities = mergeVo.getItems().stream().map(obj -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            purchaseDetailEntity.setId(obj);
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        purchaseDetailService.updateBatchById(purchaseDetailEntities);
    }

    @Transactional
    @Override
    public void receivedPurchase(List<Long> ids) {
        List<PurchaseEntity> purchaseEntities = ids.stream().map(id -> this.getById(id)).filter(item -> {
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()
                    || item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()) {
                return true;
            }
            return false;
        }).map(obj -> {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(obj.getId());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            return purchaseEntity;
        }).collect(Collectors.toList());

        this.updateBatchById(purchaseEntities);

        purchaseEntities.stream().forEach(obj -> {
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.list(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", obj.getId()));
            List<PurchaseDetailEntity> collect = purchaseDetailEntities.stream().map(item -> {
                PurchaseDetailEntity purchaseDetail = new PurchaseDetailEntity();
                purchaseDetail.setId(item.getId());
                purchaseDetail.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetail;
            }).collect(Collectors.toList());
            ;
            purchaseDetailService.updateBatchById(collect);

        });


    }

    @Override
    public void donePurchase(PurchaseDoneVo purchaseDoneVo) {
        Long purchaseId = purchaseDoneVo.getId();
        List<PurchaseItemDoneVo> purchaseItems = purchaseDoneVo.getItems();
        //更改采购项状态
        boolean flag = true;
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        for (PurchaseItemDoneVo purchaseItem : purchaseItems) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if (purchaseItem.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                flag = false;
                purchaseDetailEntity.setStatus(purchaseItem.getStatus());
            } else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
            }
            purchaseDetailEntity.setId(purchaseItem.getItemId());
            updates.add(purchaseDetailEntity);

        }
        purchaseDetailService.updateBatchById(updates);
        //更改采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        if (flag) {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
        } else {
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        }
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
        //更改库存
        updates.stream().filter(obj -> obj.getStatus() != WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode())
                .forEach(item -> {
                    PurchaseDetailEntity detailEntity = purchaseDetailService.getById(item.getId());
                    wareSkuService.addStock(detailEntity.getSkuId(), detailEntity.getWareId(), detailEntity.getSkuNum());
                });
    }


}